package org.example.bighomework.Myuser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/Myuser")
public class MyuserController {
    @Autowired
    private MyuserService MyuserService;
    //主页
    @GetMapping("/")
    public String viewHomePage(Model model){
        return findPaginated(1, "id", "asc", model);
    }

    //按角色查询
    @GetMapping("/query{Role}")
    public String query(@PathVariable(value = "Role") String Role, Model model) {

        List<Myuser> listMyuser = MyuserService.findByRole(Role);
        model.addAttribute("listMyuser", listMyuser);
        return "MyuserIndex";
    }
    //获取分页数据
    @GetMapping("/page/{pageNo}")
    public String findPaginated(@PathVariable(value = "pageNo") int pageNo,
                                @RequestParam("sortField") String sortField,
                                @RequestParam("sortDir") String sortDir,
                                Model model) {
        int pageSize = 3;
        Page<Myuser> page = MyuserService.findPaginated(pageNo, pageSize, sortField, sortDir);
        List<Myuser> listMyuser = page.getContent();

        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());
        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");
        model.addAttribute("listMyuser", listMyuser);
        return "MyuserIndex";
    }
}